<?php
namespace app\index\controller;

class push {
    public static $instance = null;
    public static $client = null;
    protected $tcp_server_url = 'tcp://127.0.0.1:5678';
    private function __construct()
    {
        $this->connect();
    }

    public function connect()
    {
         // 建立socket连接到内部推送端口
        self::$client = stream_socket_client($this->tcp_server_url, $errno, $errmsg, 1);
        return self::$client;
    }

    public static function instance()
    {
        if(self::$instance == null){
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function doPush($data)
    {
        if(!is_array($data)) return 'fail2';
        // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
        fwrite(self::$client, json_encode($data)."\n");
        // 读取推送结果
        $response = fread(self::$client, 8192);
        return trim($response);
    }

    public function __destruct()
    {
        self::$instance = null;
        self::$client = null;
    }

}